<template>
  <div class="page-content attraction-edit">
    <div class="mb-6 flex justify-between items-center">
      <div>
        <h1 class="text-2xl font-bold">{{ isEdit ? '编辑景点' : '添加景点' }}</h1>
        <p class="text-gray-500 mt-2">{{ isEdit ? '修改景点信息和资料' : '创建新的景点资料' }}</p>
      </div>
      <el-button @click="goBack">
        <el-icon><Back /></el-icon>返回
      </el-button>
    </div>

    <el-card shadow="hover">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        status-icon
        require-asterisk-position="right"
        scroll-to-error
      >
        <el-row :gutter="20">
          <!-- 基本信息 -->
          <el-col :span="24">
            <div class="form-section-title mb-4">
              <h2 class="text-lg font-medium">基本信息</h2>
              <div class="form-section-line"></div>
            </div>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="景点名称" prop="spotName">
              <el-input v-model="form.spotName" placeholder="请输入景点名称" />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="英文名称" prop="spotEnglishName">
              <el-input v-model="form.spotEnglishName" placeholder="请输入英文名称" />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="拼音名称" prop="spotPinyinName">
              <el-input v-model="form.spotPinyinName" placeholder="请输入拼音名称" />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="位置名称" prop="location">
              <div class="flex items-center w-full">
                <div class="flex-1">
                  <el-input v-model="form.location" placeholder="请选择位置" />
                </div>
                <el-button class="ml-2" @click="openMapSelection">
                  <el-icon><Location /></el-icon>
                </el-button>
              </div>
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="状态" prop="operationStatus">
              <el-select v-model="form.operationStatus" placeholder="请选择状态" class="w-full">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="开放开始时间" prop="openStartTime">
              <el-time-picker
                v-model="form.openStartTime"
                placeholder="选择时间"
                class="w-full!"
                format="HH:mm:ss"
                value-format="HHmmss"
              />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="开放结束时间" prop="openEndTime">
              <el-time-picker
                v-model="form.openEndTime"
                placeholder="选择时间"
                class="w-full!"
                format="HH:mm:ss"
                value-format="HHmmss"
              />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="开放周期" prop="openWeek">
              <el-select
                v-model="form.openWeek"
                multiple
                placeholder="请选择开放周期"
                class="w-full!"
              >
                <el-option label="星期一" :value="1" />
                <el-option label="星期二" :value="2" />
                <el-option label="星期三" :value="3" />
                <el-option label="星期四" :value="4" />
                <el-option label="星期五" :value="5" />
                <el-option label="星期六" :value="6" />
                <el-option label="星期日" :value="7" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="占地面积" prop="floorSpace">
              <el-input v-model="form.floorSpace" placeholder="例如: 15000">
                <template #append>m²</template>
              </el-input>
            </el-form-item>
          </el-col>

          <!-- 新增的营业时间输入框 -->
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="营业时间" prop="timeDescription">
              <el-input v-model="form.timeDescription" placeholder="请输入营业时间描述" />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="建成时间" prop="buildData">
              <el-date-picker
                v-model="form.buildData"
                type="date"
                placeholder="选择日期"
                class="w-full!"
                value-format="YYYYMMDD"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="景点介绍" prop="introduce">
              <el-input
                v-model="form.introduce"
                type="textarea"
                :rows="4"
                :maxlength="500"
                placeholder="请输入景点详细介绍"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="综合信息" prop="comprehensiveInfo">
              <el-input v-model="form.comprehensiveInfo" type="textarea" :rows="4" :maxlength="500"
                placeholder="请输入景点综合信息" />
            </el-form-item>
          </el-col>

          <!-- 图片管理 -->
          <el-col :span="24" class="mt-4">
            <div class="form-section-title mb-4">
              <h2 class="text-lg font-medium">图片管理</h2>
              <div class="form-section-line"></div>
            </div>
          </el-col>

          <el-col :span="24">
            <el-form-item label="主图" prop="imageUrl">
              <div class="w-full">
                <MyUpload
                  :file-list="fileList"
                  @deleteFile="deleteFile"
                  @uploadFileSuccess="success"
                />
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="相册图片">
              <div class="w-full">
                <MyUpload
                  :file-list="galleryFileList"
                  @deleteFile="galleryDeleteFile"
                  @uploadFileSuccess="gallerySuccess"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="语音">
              <div class="w-full">
                <MyUpload
                  :file-list="voiceFileList"
                  :limit="1"
                   accept=".mp3"
                  @deleteFile="voiceDeleteFile"
                  @uploadFileSuccess="voiceSuccess"
                />
                <div v-if="voiceFileList.length > 0" class="mt-2 w-[400px]">
                  <audio
                    v-for="(file, idx) in voiceFileList"
                    :key="file.path || idx"
                    :src="file.path"
                    controls
                    class="w-full"
                  >
                    您的浏览器不支持 audio 标签。
                  </audio>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="特色标签" prop="featureTag">
              <el-input
                v-model="form.featureTag"
                type="textarea"
                :rows="2"
                placeholder="请输入景点特色标签，多个标签用逗号分隔"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="2"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="form-actions mt-6 flex justify-end">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </div>
      </el-form>
    </el-card>
    <MapSelection
      v-model="mapVisible"
      :center="{
        lng: 114.17842233364557,
        lat: 30.506250728187435
      }"
      ref="mapSelectionRef"
      @confirm="handleMapConfirm"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage, FormInstance, FormRules } from 'element-plus'
  import { Back, Location } from '@element-plus/icons-vue'
  import { useWorktabStore } from '@/store/modules/worktab'
  import {
    scenicScenicSpotGetScenicSpotUsingGet,
    scenicScenicSpotSaveScenicSpotUsingPost
  } from '@/api/4a/jingdi'
  import type { ScenicSpotSaveBodc1b015330ba48a9B167200444dbf9bd } from '@/api/4a/types'
  import MapSelection from '@/components/mapSelection/index.vue'
  import { arrayToStr, strToArray } from '@/utils/utils'
  const route = useRoute()
  const router = useRouter()
  const formRef = ref<FormInstance>()
  const attractionId = ref(route.query.id ? route.query.id : undefined)
  const isEdit = computed(() => !!attractionId.value)

  // 状态选项
  const statusOptions = [
    { label: '开放中', value: 1 },
    { label: '部分维修', value: 2 },
    { label: '维护中', value: 3 },
    { label: '已关闭', value: 4 }
  ]

  // 表单数据，添加了timeDescription字段
  const form = reactive<ScenicSpotSaveBodc1b015330ba48a9B167200444dbf9bd>({
    id: undefined,
    spotName: '',
    spotEnglishName: '',
    spotPinyinName: '',
    location: '',
    locationJson: '',
    introduce: '',
    comprehensiveInfo: '', //新增综合信息字段
    imageUrl: '',
    galleryImages: '',
    audioGuide:'',
    operationStatus: 1,
    openStartTime: '',
    openEndTime: '',
    openWeek: '',
    buildData: '',
    floorSpace: '',
    timeDescription: '', // 新增的营业时间字段
    featureTag: '',
    remark: ''
  })
  const validatePass = (rule: any, value: any, callback: any) => {
    if (value && form.locationJson) {
      callback()
    } else {
      callback(new Error('请选择景点位置'))
    }
  }

  const validateComprehensiveInfo = (rule: any, value: any, callback: any) => {
    if (value && form.comprehensiveInfo) {
      // 验证字符串是否符合"name:value"格式，多个键值对以分号分隔
      const pairs = form.comprehensiveInfo.split('；')

      // 验证每一对是否符合name:value格式
      const isValid = pairs.every(pair => {
        // 检查是否包含冒号且冒号不在开头或结尾
        const colonIndex = pair.indexOf('：')
        return colonIndex > 0 && colonIndex < pair.length - 1
      })

      if (!isValid) {
        callback(new Error('格式不正确，请按照"name：value"格式填写，多个信息以分号分隔'))
      } else {
        callback()
      }
    } else {
      callback()
    }
  }

  // 表单验证规则
  const rules = reactive<FormRules>({
    spotName: [
      { required: true, message: '请输入景点名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    operationStatus: [{ required: true, message: '请选择景点状态', trigger: 'change' }],
    introduce: [
      { required: true, message: '请输入景点介绍', trigger: 'blur' },
      { min: 10, message: '介绍不能少于10个字符', trigger: 'blur' }
    ],
    comprehensiveInfo: [{ validator: validateComprehensiveInfo, trigger: 'blur' }],
    imageUrl: [{ required: true, message: '请上传景点主图', trigger: 'change' }],
    openWeek: [{ required: true, message: '请选择开放周期', trigger: 'change' }],
    buildData: [{ required: true, message: '请选择建成时间', trigger: 'change' }],
    floorSpace: [{ required: true, message: '请输入占地面积', trigger: 'blur' }],
    location: [{ validator: validatePass, trigger: 'blur' }]
  })

  // 首图
  const fileList = computed({
    get() {
      return JSON.parse(form.imageUrl || '[]')
    },
    set(value) {
      form.imageUrl = value
    }
  })

  const success = (a) => {
    fileList.value.push(a.data)
    fileList.value = JSON.stringify(fileList.value)
  }

  const deleteFile = (params) => {
    fileList.value = JSON.stringify(fileList.value.filter((item) => item.path !== params.path))
  }

  // 相册图片
  const galleryFileList = computed({
    get() {
      return JSON.parse(form.galleryImages || '[]')
    },
    set(value) {
      form.galleryImages = value
    }
  })

  const gallerySuccess = (a) => {
    galleryFileList.value.push(a.data)
    galleryFileList.value = JSON.stringify(galleryFileList.value)
  }

  const galleryDeleteFile = (params) => {
    galleryFileList.value = JSON.stringify(
      galleryFileList.value.filter((item) => item.path !== params.path)
    )
  }
// 语音
const voiceFileList = computed({
    get() {
      return JSON.parse(form.audioGuide || '[]')
    },
    set(value) {
      form.audioGuide = value
    }
  })

  const voiceSuccess = (a) => {
    voiceFileList.value.push(a.data)
    voiceFileList.value = JSON.stringify(voiceFileList.value)
  }

  const voiceDeleteFile = (params) => {
    voiceFileList.value = JSON.stringify(
      voiceFileList.value.filter((item) => item.path !== params.path)
    )
  }

  // 提交表单
  const submitForm = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      const res = await scenicScenicSpotSaveScenicSpotUsingPost({
        body: {
          ...form,
          openWeek: arrayToStr(form.openWeek),
          locationJson: JSON.stringify(form.locationJson)
        }
      })

      if (res.code === 0) {
        ElMessage.success(isEdit.value ? '景点信息更新成功' : '景点添加成功')
        router.push('/attraction/AttractionList')
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      console.error('表单验证失败', error)
      ElMessage.error('请完善表单信息')
    }
  }

  // 返回列表
  const goBack = () => {
    const worktabStore = useWorktabStore()
    worktabStore.removeTab(route.path)
    router.push('/attraction/AttractionList')
  }

  const mapSelectionRef = ref()
  // 打开地图选择
  const openMapSelection = () => {
    mapVisible.value = true
    mapSelectionRef.value.openPopup({
      lng: form.locationJson.longitude,
      lat: form.locationJson.latitude
    })
  }

  const mapVisible = ref(false)

  const handleMapConfirm = (data) => {
    // 更新位置信息
    if (data && data.point && data.surroundingPois.length > 0) {
      form.location = data.surroundingPois[0].title // 保存坐标值

      // 更新locationJson，存储完整的位置数据，兼容各个端口的字段
      form.locationJson = {
        longitude: data.point.lng, //经度
        latitude: data.point.lat, //纬度
        height: data.point.height || 0
      }

      formRef.value.validateField('location')
      mapVisible.value = false
    } else {
      ElMessage.error('请选择位置')
    }
  }

  // 获取景点详情
  const getScenicSpotDetail = async () => {
    const res = await scenicScenicSpotGetScenicSpotUsingGet({
      params: { scenicSpotId: attractionId.value }
    })

    if (res.code === 0) {
      const newData = {
        ...res.data,
        locationJson: JSON.parse(res.data?.locationJson || '{}'),
        openWeek: strToArray(res.data?.openWeek),
        // 处理音频数据
        // audioGuide: res.data?.audioGuide ? JSON.stringify([{
        //   name: '景点语音导览.mp3',
        //   path: res.data.audioGuide,
        //   type: 'audio/mp3',
        //   size: '852576'
        // }]) : '[]'
      }
      Object.assign(form, newData)
    } else {
      ElMessage.error(res.msg || '获取景点信息失败')
    }
  }

  onMounted(() => {
    if (isEdit.value) {
      getScenicSpotDetail()
    }
  })
</script>

<style lang="scss" scoped>
  :deep(.el-upload-dragger) {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
